package com.cmd.web.controller.system;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.server.HttpServerRequest;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.cmd.common.annotation.Anonymous;
import com.cmd.common.constant.Constants;
import com.cmd.common.core.domain.AjaxResult;
import com.cmd.common.core.domain.entity.SysMenu;
import com.cmd.common.core.domain.entity.SysUser;
import com.cmd.common.core.domain.model.LoginBody;
import com.cmd.common.core.domain.model.LoginUser;
import com.cmd.common.core.redis.RedisCache;
import com.cmd.common.utils.SecurityUtils;
import com.cmd.framework.config.WxAppConfig;
import com.cmd.framework.web.service.SysLoginService;
import com.cmd.framework.web.service.SysPermissionService;
import com.cmd.framework.web.service.TokenService;
import com.cmd.system.service.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Set;

/**
 * 登录验证
 *
 * @author cmd
 */
@RestController
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private WxAppConfig wxAppConfig;

    @Autowired
    private RedisCache redisCache;



    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        if (!loginUser.getPermissions().equals(permissions)) {
            loginUser.setPermissions(permissions);
            tokenService.refreshToken(loginUser);
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    @PostMapping("/wxLogin")
    public AjaxResult wxLogin(@RequestBody WxLoginBody wxLoginBody, HttpServerRequest request)
            throws UnsupportedEncodingException {
        AjaxResult ajax = AjaxResult.success();
        // 2、4
        //获取登录凭证 只能用一次
        String code = wxLoginBody.getCode();
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + wxAppConfig.getAppId() + "&secret=" + wxAppConfig.getAppSecret() + "&code=" + code + "&grant_type=authorization_code";
        String res = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.parseObject(res);
        String openid = jsonObject.getString("openid");
        String access_token = jsonObject.getString("access_token");
        String name = jsonObject.getString("name");


        String url1 = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
        String res1 = restTemplate.getForObject(url1, String.class);
        String s = new String(res1.getBytes("ISO-8859-1"), "UTF-8");
        JSONObject jsonObject1 = JSONObject.parseObject(s);
        String nickname = jsonObject1.getString("nickname");
       // String name = jsonObject.getString("name");

        //如果解析成功,获取token
        String token = loginService.wxLogin(openid,nickname);

        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    @GetMapping("/wechat-login")
    @Anonymous
    public AjaxResult wechatLogin(@RequestParam("code") String code) {

        // 2. 调用微信API换取openid
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=" + "wxd18f47635eaea06c" +
                "&secret=" + "e8c390b551cfab18218bce8180798781" +
                "&code=" + code +
                "&grant_type=authorization_code";

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        JSONObject result = JSON.parseObject(response.getBody());

        // 3. 处理微信API返回结果
        if (result.containsKey("errcode")) {
            return AjaxResult.error("微信登录失败: " + result.getString("errmsg"));
        }
        String openid = result.getString("openid");
        String token = loginService.wxLogin(openid,openid);
        AjaxResult ajax = AjaxResult.success();
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }



}
